package com.example.my_objectives.controller;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseController extends SQLiteOpenHelper {

	// Logcat tag
	private static final String	LOG					= DatabaseController.class.getName();
	private static final int		DATABASE_VERSION	= 1;
	private static final String	DATABASE_NAME		= "myObjectives";

	private SQLiteDatabase			_database;
	private Context					_context;

	public DatabaseController(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		this._context = context;
		_database = null;
	}

	public SQLiteDatabase get_database() {
		if (_database == null) {
			openDB();
		}//if
		return _database;
	}

	public void set_database(SQLiteDatabase database) {
		_database = database;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		Exception returnValue;

		HistoryController historyController = new HistoryController(_context, db);
		ObjectiveController objectiveController = new ObjectiveController(_context, db);
		RecurrenceController recurrenceController = new RecurrenceController(_context, db);
		UnitController unitController = new UnitController(_context, db);

		returnValue = unitController.createTable();
		if (returnValue != null) {
			Log.e(LOG, returnValue.getMessage());
			// TODO: display error message
		}// if

		returnValue = recurrenceController.createTable();
		if (returnValue != null) {
			Log.e(LOG, returnValue.getMessage());
			// TODO: display error message
		}// if

		returnValue = objectiveController.createTable();
		if (returnValue != null) {
			Log.e(LOG, returnValue.getMessage());
			// TODO: display error message
		}// if

		returnValue = historyController.createTable();
		if (returnValue != null) {
			Log.e(LOG, returnValue.getMessage());
			// TODO: display error message
		}// if
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO: Modify the code in order not to drop the tables
		// db.execSQL("DROP TABLE IF EXISTS " + TableName.history);
		// db.execSQL("DROP TABLE IF EXISTS " + TableName.objective);
		// db.execSQL("DROP TABLE IF EXISTS " + TableName.recurrence);

		// create new tables
		// onCreate(db);
	}

	// closing database
	public void closeDB() {
		try {
			if (_database != null && _database.isOpen()) {
				_database.close();
				Log.i(LOG, "The database is closed now.");
			}// if
		}// try
		catch (Exception e) {
			Log.e(LOG, e.getMessage());
		}// catch
	}

	public void openDB() {
		try {
			if (_database == null) {
				_database = getWritableDatabase();
				Log.i(LOG, "The database has been opened.");
			}// if
		}// try
		catch (Exception e) {
			Log.e(LOG, e.getMessage());
		}// catch
	}

	@Override
	protected void finalize() {
		closeDB();
	}

}
